package com.paradise.ytj.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.paradise.api.FacephonePreferences;
import com.paradise.ytj.R;
import com.paradise.ytj.bean.CloseEvent;
import com.paradise.ytj.bean.Constant;
import com.paradise.ytj.bean.MenuEvent;
import com.paradise.ytj.bean.OpenEvent;
import com.paradise.ytj.bean.QuitEvent;
import com.paradise.ytj.fragment.ContactFragment;
import com.paradise.ytj.fragment.MenuFragment;
import com.paradise.ytj.fragment.RecordFragment;
import com.paradise.ytj.fragment.SettingFragment;
import com.paradise.ytj.service.IncommingService;
import com.paradise.ytj.utils.ActivityUtils;
import com.paradise.ytj.utils.CameraUtils;
import com.paradise.ytj.utils.DialogUtils;
import com.paradise.ytj.utils.HomeListener;
import com.paradise.ytj.utils.SpUtils;
import com.paradise.ytj.utils.StreamUtil;
import com.paradise.ytj.view.CustomDialog;
import com.paradise.ytj.view.RoundProgressBarWidthNumber;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.paradise.api.FaceLogin;
import com.paradise.api.FacePhone;
import com.paradise.api.FacephoneListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.core.LinphoneChatMessage;
import org.linphone.core.LinphoneChatRoom;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneProxyConfig;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends FragmentActivity implements FacephoneListener.FacephoneMessageListener, FacephoneListener.FacephoneRegistrationStateListener, View.OnClickListener, View.OnFocusChangeListener {

    private TextView tvLoginState;
    private EditText etLoginAccount;
    private EditText etLoginPassword;
    private TextView btnLoginLogin;
    private RelativeLayout rlLogin;
    private int localVersionCode;
    private String description;
    private String versionCode;
    private String downloadUrl;
    private EditText etLoginName;
    private String account;
    private boolean isMenu = true;
    private String name;
    public static int currentMenuTime = 0;
    public static boolean isOnLine = false;
    /**
     * 更新新版本的状态码
     */
    protected static final int UPDATE_VERSION = 100;
    /**
     * 进入应用程序主界面状态码
     */
    protected static final int ENTER_HOME = 101;

    /**
     * url地址出错状态码
     */
    protected static final int URL_ERROR = 102;
    protected static final int IO_ERROR = 103;
    protected static final int JSON_ERROR = 104;
    private Handler mHandler = new Handler() {

        @Override
        //alt+ctrl+向下箭头,向下拷贝相同代码
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_VERSION:
                    //弹出对话框,提示用户更新
                    showUpdateDialog();
                    break;
                case ENTER_HOME:
                    //进入应用程序主界面,activity跳转过程
                    break;
                case URL_ERROR:
                    break;
                case IO_ERROR:
                    break;
                case JSON_ERROR:
                    break;
            }
        }
    };
    private RecordFragment recordFragment;
    private MenuFragment menuFragment;
    private ContactFragment contactFragment;
    private SettingFragment settingFragment;
    private FrameLayout flMain;
    private RadioGroup rgGroup;
    private RadioButton rbCall;
    private RadioButton rbRecord;
    private RadioButton rbContact;
    private RadioButton rbSetting;
    private boolean isVisicity = true;
    private int lockTime;
    private Context context;
    private AudioManager mAudioManager;
    private CustomDialog customDialog;
    private TextView tvTip;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initConfig();
        setContentView(R.layout.activity_main);
        initVar();
        initView();
        initData();
        initListener();

    }

    private void initConfig() {
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void initVar() {
        context = MainActivity.this;
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        Intent intent2 = new Intent(context, IncommingService.class);
        startService(intent2);
        ActivityUtils.addActivity(MainActivity.this);
        registerHomeListener();
    }

    /**
     * 初始化布局
     */
    private void initView() {

        tvLoginState = (TextView) findViewById(R.id.tv_login_state);
        btnLoginLogin = (TextView) findViewById(R.id.btn_login_login);
        rlLogin = (RelativeLayout) findViewById(R.id.rl_login);
        rgGroup = (RadioGroup) findViewById(R.id.rg_group);
        flMain = (FrameLayout) findViewById(R.id.fl_main);
        tvTip = (TextView) findViewById(R.id.tv_tip);

        etLoginAccount = (EditText) findViewById(R.id.et_login_account);
        etLoginPassword = (EditText) findViewById(R.id.et_login_password);
        etLoginName = (EditText) findViewById(R.id.et_login_name);
        setCursorDrawableColor(etLoginAccount, Color.WHITE);
        setCursorDrawableColor(etLoginName, Color.WHITE);
        setCursorDrawableColor(etLoginPassword, Color.WHITE);
        rbCall = (RadioButton) findViewById(R.id.rb_call);
        rbRecord = (RadioButton) findViewById(R.id.rb_record);
        rbContact = (RadioButton) findViewById(R.id.rb_contact);
        rbSetting = (RadioButton) findViewById(R.id.rb_setting);


    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (FaceLogin.instance().getCurrentAuthInfo() == null) {
            flMain.setVisibility(View.GONE);
            rlLogin.setVisibility(View.VISIBLE);
            rgGroup.setVisibility(View.GONE);
        } else {
            FacePhone.instance().getmLc().setNetworkReachable(true);
            FacePhone.instance().getmLc().refreshRegisters();
            flMain.setVisibility(View.VISIBLE);
            rlLogin.setVisibility(View.GONE);
            rgGroup.setVisibility(View.VISIBLE);
            loginState(2);
            initMenuTime();
        }

        SpUtils.putBoolean(context, Constant.ISBACK_NAME, false);

        /**
         * 更新软件
         */
        updateSoft();
    }

    /**
     * 初始化pager時間控制器
     */
    private void initMenuTime() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isVisicity) {
                    try {
                        Thread.sleep(1000);
                        currentMenuTime++;
                        try {
                            lockTime = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
                        } catch (Settings.SettingNotFoundException e) {
                            e.printStackTrace();
                            lockTime = 5 * 60;
                        }
                        if (currentMenuTime >= lockTime / 1000 / 2) {
                            if (flMain.getVisibility() == View.VISIBLE) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        flMain.setVisibility(View.GONE);
                                        rgGroup.setVisibility(View.GONE);
                                    }
                                });

                            }
                        }
                        if (currentMenuTime >= lockTime / 1000) {
                            CloseEvent event = new CloseEvent();
                            EventBus.getDefault().post(event);
                            currentMenuTime = 0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {

        FacePhone.instance().addMessageListener(this);
        FacePhone.instance().addRegistrationStateListener(this);
        EventBus.getDefault().register(this);

        btnLoginLogin.setOnClickListener(this);
        etLoginPassword.setOnClickListener(this);
        etLoginAccount.setOnClickListener(this);
        etLoginName.setOnClickListener(this);

        rbCall.setOnClickListener(this);
        rbRecord.setOnClickListener(this);
        rbContact.setOnClickListener(this);
        rbSetting.setOnClickListener(this);

        etLoginAccount.setOnFocusChangeListener(this);
        etLoginName.setOnFocusChangeListener(this);
        etLoginPassword.setOnFocusChangeListener(this);
        rbCall.setOnFocusChangeListener(this);
        rbRecord.setOnFocusChangeListener(this);
        rbContact.setOnFocusChangeListener(this);
        rbSetting.setOnFocusChangeListener(this);
        btnLoginLogin.setOnFocusChangeListener(this);

    }

    @Override
    public void onClick(View view) {
        currentMenuTime = 0;
        switch (view.getId()) {
            case R.id.btn_login_login:
                if (CameraUtils.getNumber() == 0) {
                    Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                    return;
                }
                account = etLoginAccount.getText().toString().trim();
                if (TextUtils.isEmpty(account)) {
                    return;
                }
                String password = etLoginPassword.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    return;
                }
                name = etLoginName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    name = account;
                }
                String proxy = SpUtils.getString(context, Constant.PROXY_NAME, Constant.PROXY);
                String ip = SpUtils.getString(context, Constant.DOMAIN_NAME, Constant.IP);
                String protocol = SpUtils.getString(context, Constant.PROCOTOL_NAME, Constant.PROTOCOL);
                FaceLogin.instance().regist(context, name, account, password, ip, proxy, protocol);
                etLoginAccount.setText("");
                etLoginPassword.setText("");
                etLoginName.setText("");
                flMain.setVisibility(View.VISIBLE);
                rlLogin.setVisibility(View.GONE);
                rgGroup.setVisibility(View.VISIBLE);
                rbCall.requestFocus();
                break;

            case R.id.et_login_account:
                etLoginAccount.setInputType(InputType.TYPE_CLASS_NUMBER);
                etLoginAccount.requestFocus();
                InputMethodManager imm1 = (InputMethodManager) etLoginAccount.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.showSoftInput(etLoginAccount, 0);
                break;

            case R.id.et_login_name:
                etLoginName.setInputType(InputType.TYPE_CLASS_TEXT);
                etLoginName.requestFocus();
                InputMethodManager imm2 = (InputMethodManager) etLoginName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.showSoftInput(etLoginName, 0);
                break;

            case R.id.et_login_password:
                etLoginPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
                etLoginPassword.requestFocus();
                InputMethodManager imm3 = (InputMethodManager) etLoginPassword.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm3.showSoftInput(etLoginPassword, 0);
                break;
            case R.id.rb_call:
                rbCall.requestFocus();
                if (menuFragment == null) {
                    menuFragment = new MenuFragment();
                    changeFragment(menuFragment);
                }
                isMenu = true;
                break;

            case R.id.rb_record:
                rbRecord.requestFocus();
                if (recordFragment == null) {
                    recordFragment = new RecordFragment();
                    changeFragment(recordFragment);
                }
                isMenu = false;
                break;

            case R.id.rb_contact:
                rbContact.requestFocus();
                if (contactFragment == null) {
                    contactFragment = new ContactFragment();
                    changeFragment(contactFragment);
                }
                isMenu = false;
                break;

            case R.id.rb_setting:
                rbSetting.requestFocus();
                if (settingFragment == null) {
                    settingFragment = new SettingFragment();
                    changeFragment(settingFragment);
                }
                isMenu = false;
                break;

        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.rb_call:
                if (hasFocus) {
                    boolean isback = SpUtils.getBoolean(context, Constant.ISBACK_NAME, false);
                    if (isback == false) {
                        if (menuFragment == null) {
                            menuFragment = new MenuFragment();
                        }
                        changeFragment(menuFragment);
                        isMenu = true;
                    }
                    zoomOut(rbCall);
                } else {
                    zoomIn(rbCall);
                }
                break;

            case R.id.rb_record:
                if (hasFocus) {
                    if (recordFragment == null) {
                        recordFragment = new RecordFragment();
                    }
                    changeFragment(recordFragment);
                    isMenu = false;
                    zoomOut(rbRecord);
                } else {
                    zoomIn(rbRecord);
                }
                break;

            case R.id.rb_contact:
                if (hasFocus) {
                    if (contactFragment == null) {
                        contactFragment = new ContactFragment();
                    }
                    changeFragment(contactFragment);
                    isMenu = false;
                    zoomOut(rbContact);
                } else {
                    zoomIn(rbContact);
                }
                break;

            case R.id.rb_setting:
                if (hasFocus) {
                    if (settingFragment == null) {
                        settingFragment = new SettingFragment();
                    }
                    changeFragment(settingFragment);
                    isMenu = false;
                    zoomOut(rbSetting);
                } else {
                    zoomIn(rbSetting);
                }
                break;
            case R.id.et_login_name:
                if (hasFocus) {
                    tvTip.setVisibility(View.VISIBLE);
                } else {
                    tvTip.setVisibility(View.INVISIBLE);
                }
                break;

        }
    }

    @Override
    public void messageReceived(LinphoneCore linphoneCore, LinphoneChatRoom linphoneChatRoom, LinphoneChatMessage linphoneChatMessage) {
        Toast.makeText(this, linphoneChatMessage.getFrom().getUserName() + "message" + linphoneChatMessage.getText(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void registrationState(LinphoneCore linphoneCore, LinphoneProxyConfig linphoneProxyConfig, LinphoneCore.RegistrationState registrationState, String s) {
        Log.e("para", "message" + s);
        if (registrationState == LinphoneCore.RegistrationState.RegistrationOk) {
            loginState(1);
            isOnLine = true;
        } else if (registrationState == LinphoneCore.RegistrationState.RegistrationProgress) {
            loginState(3);
        } else if (registrationState == LinphoneCore.RegistrationState.RegistrationFailed) {
            Log.e("para", "RegistrationFailed");
            loginState(2);
            isOnLine = false;
        } else if (registrationState == LinphoneCore.RegistrationState.RegistrationNone) {
        }
    }

    /**
     * 有四种取值
     *
     * @param id 0：未登录 1:登录成功 2：登录失败 3:正在登录
     */
    private void loginState(int id) {
        switch (id) {
            case 0:
                tvLoginState.setText(R.string.state_unlogin);
                tvLoginState.setTextColor(getResources().getColor(R.color.login_un));
                tvLoginState.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.login_un), null, null, null);
                break;
            case 1:
                tvLoginState.setText(R.string.state_login);
                tvLoginState.setTextColor(getResources().getColor(R.color.login_success));
                tvLoginState.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.login_success), null, null, null);
                tvLoginState.append("\t" + FaceLogin.instance().getCurrentAuthInfo().getUsername());
                break;
            case 2:
                tvLoginState.setText(R.string.state_fail);
                tvLoginState.setTextColor(getResources().getColor(R.color.login_fail));
                tvLoginState.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.login_fail), null, null, null);
                tvLoginState.append("\t" + FaceLogin.instance().getCurrentAuthInfo().getUsername());
                break;
            case 3:
                tvLoginState.setText(R.string.state_ing);
                tvLoginState.setTextColor(getResources().getColor(R.color.login_un));
                tvLoginState.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.login_un), null, null, null);
                tvLoginState.append("\t" + FaceLogin.instance().getCurrentAuthInfo().getUsername());
                break;
        }
    }


    /**
     * 更新软件
     */
    private void updateSoft() {
        localVersionCode = getVersionCode();
        checkVersion();
    }

    /**
     * 返回版本号
     *
     * @return 非0 则代表获取成功
     */
    private int getVersionCode() {
        //1,包管理者对象packageManager
        PackageManager pm = getPackageManager();
        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            //3,获取版本名称
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 检测版本号
     */
    private void checkVersion() {
        new Thread() {
            public void run() {
                //发送请求获取数据,参数则为请求json的链接地址
                //仅限于模拟器访问电脑tomcat
                Message msg = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    //1,封装url地址
                    URL url = new URL(Constant.UPLOAD_URI);
                    //2,开启一个链接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //3,设置常见请求参数(请求头)

                    //请求超时
                    connection.setConnectTimeout(2000);
                    //读取超时
                    connection.setReadTimeout(2000);

                    //4,获取请求成功响应码
                    if (connection.getResponseCode() == 200) {
                        //5,以流的形式,将数据获取下来
                        InputStream is = connection.getInputStream();
                        //6,将流转换成字符串(工具类封装)
                        String json = StreamUtil.streamToString(is);
                        //7,json解析
                        JSONObject jsonObject = new JSONObject(json);

                        //debug调试,解决问题
                        description = jsonObject.getString("description");
                        versionCode = jsonObject.getString("versionCode");
                        downloadUrl = jsonObject.getString("downloadUrl");

                        //8,比对版本号(服务器版本号>本地版本号,提示用户更新)
                        if (localVersionCode < Integer.parseInt(versionCode)) {
                            //提示用户更新,弹出对话框(UI),消息机制
                            msg.what = UPDATE_VERSION;
                        } else {
                            //进入应用程序主界面
                            msg.what = ENTER_HOME;
                        }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    msg.what = URL_ERROR;
                } catch (IOException e) {
                    e.printStackTrace();
                    msg.what = IO_ERROR;
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.what = JSON_ERROR;
                } finally {
                    //指定睡眠时间,请求网络的时长超过4秒则不做处理
                    //请求网络的时长小于4秒,强制让其睡眠满4秒钟
                    long endTime = System.currentTimeMillis();
                    if (endTime - startTime < 4000) {
                        try {
                            Thread.sleep(4000 - (endTime - startTime));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }

    /**
     * 弹出对话框,提示用户更新
     */
    protected void showUpdateDialog() {
        boolean update = SpUtils.getBoolean(context, Constant.UPDATE_NAME, Constant.UPDATE_DEFAULT);
        if (update) {
            customDialog = new CustomDialog(context);
            if (!isFinishing()) {
                customDialog.show();

            }
            View inflate = View.inflate(context, R.layout.dialog_update_hint, null);
            TextView tvDescription = (TextView) inflate.findViewById(R.id.tv_description);
            customDialog.setTitleText("版本更新");
            customDialog.setDeclareText("推荐立即更新软件，以便带来更佳稳定和流程的软件体验");
            customDialog.setCancelText("以后再说");
            customDialog.setSubmitText("立即更新");
            customDialog.getContentView().addView(inflate);
            tvDescription.setText(description);
            customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
                @Override
                public void onCancelClick() {
                    customDialog.dismiss();

                }
            });
            customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
                @Override
                public void onSubmitClick() {
                    customDialog.dismiss();
                    downloadApk();
                }
            });
        }
    }

    protected void downloadApk() {
        final CustomDialog customDialog = new CustomDialog(context);
        if (!isFinishing()) {
            customDialog.show();
        }
        View inflate = View.inflate(context, R.layout.dialog_update_progress, null);
        final RoundProgressBarWidthNumber barWidthNumber = (RoundProgressBarWidthNumber) inflate.findViewById(R.id.rpb_progress);
        customDialog.setTitleText("下载进度");
        customDialog.setDeclareText("正在下载请稍后");
        customDialog.getContentView().addView(inflate);
        customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
            @Override
            public void onCancelClick() {

            }
        });
        customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
            @Override
            public void onSubmitClick() {

            }
        });
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "para.apk";
            HttpUtils httpUtils = new HttpUtils();
            httpUtils.download(downloadUrl, path, new RequestCallBack<File>() {
                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    File file = responseInfo.result;
                    installApk(file);
                    customDialog.dismiss();
                }

                @Override
                public void onFailure(com.lidroid.xutils.exception.HttpException error, String msg) {
                    customDialog.dismiss();
                    Toast.makeText(context, R.string.add_fail, Toast.LENGTH_SHORT).show();
                }

                //刚刚开始下载方法
                @Override
                public void onStart() {
                    super.onStart();
                }

                //下载过程中的方法(下载apk总大小,当前的下载位置,是否正在下载)
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    barWidthNumber.setProgress((int) (((current * 1.0) / total) * 100));
                }
            });

        }
    }

    /**
     * 安装对应apk
     *
     * @param file 安装文件
     */
    protected void installApk(File file) {
        //系统应用界面,源码,安装apk入口
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getQuit(QuitEvent quitEvent) {
        FaceLogin.instance().logoutCurrentUser();
        FacePhone.instance().getmLc().clearProxyConfigs();
        FacePhone.instance().getmLc().clearAuthInfos();
        if (FacephonePreferences.instance().getAccountCount() == 0) {
            FaceLogin.instance().alterDisplayName(name);
            loginState(0);
            rlLogin.setVisibility(View.VISIBLE);
            flMain.setVisibility(View.GONE);
            rgGroup.setVisibility(View.GONE);
            etLoginName.setText(FacephonePreferences.instance().getAccountDisplayName(FacephonePreferences.instance().getAccountCount() - 1));
        } else {
            Toast.makeText(context, "操作失败!", Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    protected void onDestroy() {
        ActivityUtils.removeActivity(MainActivity.this);
        mHomeWatcher.stopWatch();
        SpUtils.putBoolean(context, Constant.ISBACK_NAME, true);
        mAudioManager.setParameters("uac_enable=off");
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    private void changeFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_main, fragment);
        transaction.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        currentMenuTime = 0;
        if (FaceLogin.instance().getCurrentAuthInfo() != null) {
            if (flMain.getVisibility() == View.GONE) {
                flMain.setVisibility(View.VISIBLE);
            }
            if (rgGroup.getVisibility() == View.GONE) {
                rgGroup.setVisibility(View.VISIBLE);
                rbCall.requestFocus();
            }
        } else {
            if (rlLogin.getVisibility() == View.GONE) {
                rlLogin.setVisibility(View.VISIBLE);
                flMain.setVisibility(View.GONE);
                rgGroup.setVisibility(View.GONE);
            }
        }
        if (keyCode == 7 || keyCode == 8 ||
                keyCode == 9 || keyCode == 10 ||
                keyCode == 11 || keyCode == 12 ||
                keyCode == 13 || keyCode == 14 ||
                keyCode == 15 || keyCode == 16 &&
                FaceLogin.instance().getCurrentAuthInfo() != null) {
            if (isMenu == false) {
                rbCall.requestFocus();
            }
            MenuEvent menuEvent = new MenuEvent();
            menuEvent.setKey(keyCode);
            EventBus.getDefault().post(menuEvent);

        }
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            if (pm.isInteractive()) {
                OpenEvent event1 = new OpenEvent();
                EventBus.getDefault().post(event1);
            }
        } else {
            if (pm.isScreenOn()) {
                OpenEvent event1 = new OpenEvent();
                EventBus.getDefault().post(event1);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentMenuTime = 0;
        if (FaceLogin.instance().getCurrentAuthInfo() != null) {
            if (flMain.getVisibility() == View.GONE) {
                flMain.setVisibility(View.VISIBLE);
            }
            if (rgGroup.getVisibility() == View.GONE) {
                rgGroup.setVisibility(View.VISIBLE);
                rbCall.requestFocus();
            }
        } else {
            if (rlLogin.getVisibility() == View.GONE) {
                rlLogin.setVisibility(View.VISIBLE);
                flMain.setVisibility(View.GONE);
                rgGroup.setVisibility(View.GONE);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isVisicity = false;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        isVisicity = true;
        initMenuTime();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        currentMenuTime = 0;
        return super.dispatchTouchEvent(ev);
    }


    private void zoomOut(RadioButton radioButton) {
        ScaleAnimation animation = new ScaleAnimation(1f,
                1.05f,
                1f,
                1.05f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);
        animation.setDuration(200);
        animation.setFillAfter(true);
        radioButton.startAnimation(animation);
    }

    private void zoomIn(RadioButton radioButton) {
        ScaleAnimation animation = new ScaleAnimation(1.05f,
                1f,
                1.05f,
                1f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);
        animation.setDuration(200);
        animation.setFillAfter(true);
        radioButton.startAnimation(animation);
    }

    @Override
    public void onBackPressed() {
        if (!isMenu) {
            rbCall.requestFocus();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 代码设置光标颜色
     *
     * @param editText 你使用的EditText
     * @param color    光标颜色
     */
    public void setCursorDrawableColor(EditText editText, int color) {
        try {
            Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");//获取这个字段
            fCursorDrawableRes.setAccessible(true);//代表这个字段、方法等等可以被访问
            int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);

            Field fEditor = TextView.class.getDeclaredField("mEditor");
            fEditor.setAccessible(true);
            Object editor = fEditor.get(editText);

            Class<?> clazz = editor.getClass();
            Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
            fCursorDrawable.setAccessible(true);

            Drawable[] drawables = new Drawable[2];
            drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
            drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);//SRC_IN 上下层都显示。下层居上显示。
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            fCursorDrawable.set(editor, drawables);
        } catch (Throwable ignored) {
        }
    }


    private HomeListener mHomeWatcher;

    /**
     * 注册Home键的监听
     */
    private void registerHomeListener() {
        mHomeWatcher = new HomeListener(this);
        mHomeWatcher.setOnHomePressedListener(new HomeListener.OnHomePressedListener() {

            @Override
            public void onHomePressed() {
                ActivityUtils.removeALLActivity();
                DialogUtils.removeALLDialog();
            }

            @Override
            public void onHomeLongPressed() {

            }
        });
        mHomeWatcher.startWatch();
    }
}